﻿using Dapper;
using System;
using BCEntity.Trading.Purchase.GoodsPurchaseCertificate;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using BCCommon;

namespace BCData.Trading.Purchase.GoodsPurchaseCertificate
{
    /// <summary>
    /// 商品采购单记账凭证
    /// </summary>
    public class GoodsPurchaseCertificateData : IGoodsPurchaseCertificateData
    {
        private readonly IDatabaseContext databaseContext;
        private const string QUERY_EXISTS = @"SELECT 1 FROM goodspurchasecertificate";
        private const string QUERY = @"SELECT GoodsPurchaseCertificateId,GoodsPurchaseId,GoodsPurchaseNo,CertificateNo,PaidType,CreateTime,CreateAdminId,CreateAdminName FROM goodspurchasecertificate";
        public GoodsPurchaseCertificateData(IDatabaseContext databaseContext)
        {
            this.databaseContext = databaseContext;
        }
        #region 检查商品采购单记账凭证是否存在
        public async Task<bool> Exists(long goodsPurchaseCertificateId)
        {
            string sql = string.Format(@"{0} WHERE GoodsPurchaseCertificateId=?GoodsPurchaseCertificateId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?GoodsPurchaseCertificateId", goodsPurchaseCertificateId, DbType.Int64);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }

        public async Task<bool> Exists(string certificateNo)
        {
            string sql = string.Format(@"{0} WHERE CertificateNo=?CertificateNo", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?CertificateNo", certificateNo?.Trim(), DbType.AnsiString);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }
        #endregion

        #region 添加商品采购单记账凭证
        public async Task<GoodsPurchaseCertificateEntity> Add(GoodsPurchaseCertificateEntity entity)
        {
            string sql = SqlCommands.GetInsertSql("goodspurchasecertificate", new string[] { "GoodsPurchaseId", "GoodsPurchaseNo", "CertificateNo", "PaidType", "CreateAdminId", "CreateAdminName" });
            sql = string.Format("{0} {1} WHERE GoodsPurchaseCertificateId=LAST_INSERT_ID();", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?GoodsPurchaseId", entity.GoodsPurchaseId, DbType.Int64, size: 20);
            parameters.Add("?GoodsPurchaseNo", entity.GoodsPurchaseNo?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?CertificateNo", entity.CertificateNo?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?PaidType", entity.PaidType.ToString(), DbType.AnsiString);
            parameters.Add("?CreateAdminId", entity.CreateAdminId, DbType.Int64, size: 20);
            parameters.Add("?CreateAdminName", entity.CreateAdminName?.Trim(), DbType.AnsiString, size: 20);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<GoodsPurchaseCertificateEntity>(sql, parameters, databaseContext.Transaction);

        }
        #endregion

        #region 修改商品采购单记账凭证
        public async Task<GoodsPurchaseCertificateEntity> Update(GoodsPurchaseCertificateEntity entity)
        {
            string sql = SqlCommands.GetUpdateSql("goodspurchasecertificate", new string[] { "GoodsPurchaseId", "GoodsPurchaseNo", "CertificateNo", "PaidType", "CreateAdminId", "CreateAdminName" }, new string[] { "GoodsPurchaseCertificateId" });
            sql = string.Format("{0} {1} WHERE GoodsPurchaseCertificateId=?GoodsPurchaseCertificateId;", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?GoodsPurchaseCertificateId", entity.GoodsPurchaseCertificateId, DbType.Int64, size: 20);
            parameters.Add("?GoodsPurchaseId", entity.GoodsPurchaseId, DbType.Int64, size: 20);
            parameters.Add("?GoodsPurchaseNo", entity.GoodsPurchaseNo?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?CertificateNo", entity.CertificateNo?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?PaidType", entity.PaidType.ToString(), DbType.AnsiString);
            parameters.Add("?CreateAdminId", entity.CreateAdminId, DbType.Int64, size: 20);
            parameters.Add("?CreateAdminName", entity.CreateAdminName?.Trim(), DbType.AnsiString, size: 20);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<GoodsPurchaseCertificateEntity>(sql, parameters, databaseContext.Transaction);
        }
        #endregion

        #region 删除商品采购单记账凭证
        public async Task<bool> Delete(long goodsPurchaseCertificateId)
        {
            string sql = @"DELETE FROM goodspurchasecertificate WHERE GoodsPurchaseCertificateId=?GoodsPurchaseCertificateId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?GoodsPurchaseCertificateId", goodsPurchaseCertificateId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }
        #endregion

        #region 获取商品采购单记账凭证
        public async Task<GoodsPurchaseCertificateEntity> GetEntity(long goodsPurchaseCertificateId)
        {
            string sql = string.Format(@"{0} WHERE GoodsPurchaseCertificateId=?GoodsPurchaseCertificateId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?GoodsPurchaseCertificateId", goodsPurchaseCertificateId, DbType.Int64);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<GoodsPurchaseCertificateEntity>(sql, parameters);
        }
        #endregion

        #region 获取商品采购单记账凭证列表
        public async Task<IEnumerable<GoodsPurchaseCertificateEntity>> GetList(long goodsPurchaseId)
        {
            string sql = string.Format(@"{0} WHERE GoodsPurchaseId=?GoodsPurchaseId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?GoodsPurchaseId", goodsPurchaseId, DbType.Int64);
            return await this.databaseContext.Slave.QueryAsync<GoodsPurchaseCertificateEntity>(sql, parameters);
        }
        #endregion

        #region 获取商品采购单记账凭证分页
        public async Task<(IEnumerable<GoodsPurchaseCertificateEntity>, int)> Query(long? goodsPurchaseId,string certificateNo, DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            if (goodsPurchaseId.HasValue)
            {
                wheres.Add("GoodsPurchaseId=?GoodsPurchaseId");
                parameters.Add("?GoodsPurchaseId", goodsPurchaseId, DbType.Int64);
            }
            if (!string.IsNullOrWhiteSpace(certificateNo))
            {
                wheres.Add("CertificateNo LIKE CONCAT('%',CONCAT(?CertificateNo,'%'))");
                parameters.Add("?CertificateNo", certificateNo?.Trim(), DbType.AnsiString);
            }
            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("CreateTime>=?Start");
                parameters.Add("?Start", start.Value, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime<=?End");
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime>=?Start AND CreateTime<=?End");
                parameters.Add("?Start", start.Value, DbType.DateTime);
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            string sql = string.Format(@"{0} {1} ORDER BY {4} {5} LIMIT {2},{3}; SELECT COUNT(1) FROM goodspurchasecertificate {1}",
                  QUERY,
                  wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                  (pageIndex == 0 ? 0 : pageIndex - 1) * pageSize,
                  pageSize,
                  string.IsNullOrWhiteSpace(sortName) ? "CreateTime" : sortName,
                  ascending.HasValue && ascending.Value ? "ASC" : "DESC");
            return await this.databaseContext.Slave.QueryMultipleAsync<GoodsPurchaseCertificateEntity, int>(sql, parameters);
        }
        #endregion
    }
}



